import axios from "axios";
import { Request } from "express";
import Types from "../typings";

export const post = (
  req: Request,
  url: string,
  data: Types.Common.PlainObjType = {}
) => {
  return new Promise((resolve, reject) => {
    const authorization = req.headers.authorization;
    axios
      .post(`http://127.0.0.1:${process.env.PORT}${url}`, data, {
        headers: { authorization },
      })
      .then((resp) => {
        if (resp.data.code === 0) {
          resolve(resp.data.data as Types.Common.PlainObjType);
        } else {
          reject("code 不正确");
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const get = (
  req: Request,
  url: string,
  data: Types.Common.PlainObjType = {}
) => {
  return new Promise((resolve, reject) => {
    const authorization = req.headers.authorization;
    axios
      .get(`http://127.0.0.1:${process.env.PORT}${url}`, {
        params: data,
        headers: { authorization },
      })
      .then((resp) => {
        if (resp.data.code === 0) {
          resolve(resp.data.data as Types.Common.PlainObjType);
        } else {
          reject("code 不正确");
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};
